#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

int size =  sizeof(struct sockaddr_in); 
int sockfd;

//接收线程回调函数
void *func ()
{
        char * R_recmsg = calloc(1,128);
        int rec = -1;
        while(1)
        {
            printf("等待Jack发送信息...");
            bzero(R_recmsg,128);
            
            int rec =  recv(sockfd, R_recmsg , 128 , 0 );
            if(rec == -1)
            {
                perror("Rose接受信息失败\n");
                break;
            }
            else
            {
                printf("Rose收到消息:%s\n",R_recmsg);
            }
        }
       
}


int main(int argc, char const *argv[])
{
    
    //购买手机（创建网络编程接口）
    sockfd = socket( AF_INET, SOCK_STREAM , 0);
    if(sockfd == -1)
    {
        perror("socket  faile\n");
        return -1;
    }
    
    //买电话卡（对方IP以及端口号的设置）
     // struct sockaddr_in {
    // sa_family_t     sin_family;     /* AF_INET */
    // in_port_t       sin_port;       /* Port number */
    // struct in_addr  sin_addr;       /* IPv4 address */
    // };
    struct sockaddr_in rec_addr = {0};
    rec_addr.sin_family = AF_INET;
    rec_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    rec_addr.sin_port = htons(65001);


    //打电话给对方
    if(connect(sockfd , (struct sockaddr *)&rec_addr, size))
    {
        perror("connect faile");
        return -1;
    }
    else
    {
        printf("连接成功\n");
    }
    
    //创建线程接收信息
    pthread_t thread;
    int  m = pthread_create(&thread, NULL , func , NULL);
    if(m)
    {
        perror("pthread error\n");
        return -1;
    }
    else
    {
        printf("线程创建成功\n");
    }

    
    //开始交流发送信息
    char * send_msg = calloc(1,128);
    int ret_byte = -1;

    while(1)
    {   
        printf("请输入要发送的信息：\n");
        fgets( send_msg , 128 , stdin );

        ret_byte =  send(sockfd, send_msg, 128 , 0);
        if(ret_byte == -1)
        {
            perror("recive faile\n");
            return -1;
        }
        else
        {
            printf("ret_byte :%d msg:%s",ret_byte,send_msg);
        }

    }


    //关闭套接字
   // close(sockfd);

    return 0;
}
